package org.example.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * MQTT 消息出站配置
 *
 * @author Brant
 * @since 2025-04-21
 */
@Configuration
@Slf4j
public class MqttOutboundConfiguration {
    /**
     * MQTT 属性配置
     */
    @Autowired
    private MqttPropertiesConfig mqttPropertiesConfig;
    /**
     * MQTT 客户端工厂
     */
    @Autowired
    private MqttPahoClientFactory mqttPahoClientFactory;

    /**
     * 消息通道
     *
     * @return 消息通道
     */
    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    /**
     * 配置出站消息处理器
     *
     * @return 消息处理器
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")  // 指定处理器针对哪个通道的消息进行处理
    public MessageHandler mqttOutboundMessageHandler() {
        MqttPahoMessageHandler mqttPahoMessageHandler = new MqttPahoMessageHandler(
            mqttPropertiesConfig.getUrl(),
            mqttPropertiesConfig.getPubClientId(),
            mqttPahoClientFactory
        );
        mqttPahoMessageHandler.setDefaultQos(1);
        mqttPahoMessageHandler.setDefaultTopic(mqttPropertiesConfig.getPubTopic());
        mqttPahoMessageHandler.setAsync(true);
        return mqttPahoMessageHandler;
    }

}